from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from base import models as baseModels
# 1. 客户模型（核心实体）
class CrmCustomer(models.Model):
    CUSTOMER_TYPE = (
        ("individual", "个人客户"),
        ("enterprise", "企业客户"),
    )
    name = models.CharField("客户名称", max_length=100)
    type = models.CharField("客户类型", max_length=20, choices=CUSTOMER_TYPE)
    industry = models.CharField("所属行业", max_length=50, blank=True)  # 仅企业客户可能需要
    phone = models.CharField("联系电话", max_length=20)
    email = models.EmailField("邮箱", blank=True)
    address = models.TextField("地址", blank=True)
    source = models.CharField("客户来源", max_length=50, blank=True)  # 如：官网、转介绍
    status = models.CharField("客户状态", max_length=20, default="active")  # active/inactive
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_customers",
        verbose_name="创建人"
    )
    assigned_to = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="assigned_customers",
        verbose_name="负责人"
    )
    created_at = models.DateTimeField("创建时间", default=timezone.now)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "客户"
        verbose_name_plural = "客户"
        ordering = ["-created_at"]


# 2. 联系人模型（关联客户，一个客户可多个联系人）
class Contact(models.Model):
    customer = models.ForeignKey(
        CrmCustomer,
        on_delete=models.CASCADE,
        related_name="contacts",
        verbose_name="关联客户"
    )
    name = models.CharField("联系人姓名", max_length=50)
    position = models.CharField("职位", max_length=50, blank=True)  # 如：经理、采购
    phone = models.CharField("联系电话", max_length=20)
    email = models.EmailField("邮箱", blank=True)
    is_primary = models.BooleanField("是否主要联系人", default=False)  # 标记核心对接人
    notes = models.TextField("备注", blank=True)
    created_at = models.DateTimeField("创建时间", default=timezone.now)

    def __str__(self):
        return f"{self.customer.name} - {self.name}"

    class Meta:
        verbose_name = "联系人"
        verbose_name_plural = "联系人"


# 3. 销售机会模型（潜在订单）
class Opportunity(models.Model):
    STAGE = (
        ("initial", "初步接触"),
        ("needs", "需求确认"),
        ("proposal", "方案提交"),
        ("negotiation", "商务谈判"),
        ("closed_won", "已成交"),
        ("closed_lost", "已失败"),
    )
    customer = models.ForeignKey(
        CrmCustomer,
        on_delete=models.CASCADE,
        related_name="opportunities",
        verbose_name="关联客户"
    )
    title = models.CharField("机会名称", max_length=100)  # 如：XX公司ERP系统采购
    amount = models.DecimalField("预计金额", max_digits=12, decimal_places=2)
    stage = models.CharField("阶段", max_length=20, choices=STAGE, default="initial")
    probability = models.IntegerField("成交概率(%)", default=0)  # 0-100
    expected_close_date = models.DateField("预计成交日期", null=True, blank=True)
    products = models.ManyToManyField(
        baseModels.FinishedModel,
        related_name="opportunities",
        blank=True,
        verbose_name="关联产品"
    )
    assigned_to = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="assigned_opportunities",
        verbose_name="负责人"
    )
    notes = models.TextField("备注", blank=True)
    created_at = models.DateTimeField("创建时间", default=timezone.now)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        verbose_name = "销售机会"
        verbose_name_plural = "销售机会"

    def __str__(self):
        return self.title
# 4. 跟进记录模型（客户/机会的互动记录）
class FollowUp(models.Model):
    FOLLOW_TYPE = (
        ("call", "电话沟通"),
        ("meeting", "面谈"),
        ("email", "邮件"),
        ("other", "其他"),
    )
    # 支持关联客户或销售机会（二选一，通过 null=True 实现）
    customer = models.ForeignKey(
        CrmCustomer,
        on_delete=models.CASCADE,
        related_name="follow_ups",
        null=True,
        blank=True,
        verbose_name="关联客户"
    )
    opportunity = models.ForeignKey(
        Opportunity,
        on_delete=models.CASCADE,
        related_name="follow_ups",
        null=True,
        blank=True,
        verbose_name="关联销售机会"
    )
    content = models.TextField("跟进内容")  # 记录沟通详情
    follow_type = models.CharField("跟进方式", max_length=20, choices=FOLLOW_TYPE)
    follow_date = models.DateTimeField("跟进时间", default=timezone.now)
    next_follow_date = models.DateTimeField("下次跟进时间", null=True, blank=True)  # 提醒
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_follow_ups",
        verbose_name="跟进人"
    )

    def clean(self):
        # 校验：必须关联客户或销售机会中的一个
        from django.core.exceptions import ValidationError
        if not self.customer and not self.opportunity:
            raise ValidationError("必须关联客户或销售机会")

    class Meta:
        verbose_name = "跟进记录"
        verbose_name_plural = "跟进记录"
        ordering = ["-follow_date"]





# 6. 订单模型（已成交的销售）
class Order(models.Model):
    ORDER_STATUS = (
        ("pending", "待付款"),
        ("paid", "已付款"),
        ("completed", "已完成"),
        ("cancelled", "已取消"),
    )
    order_no = models.CharField("订单编号", max_length=50, unique=True)  # 如：ORD20231030001
    customer = models.ForeignKey(
        CrmCustomer,
        on_delete=models.CASCADE,
        related_name="orders",
        verbose_name="客户"
    )
    opportunity = models.ForeignKey(
        Opportunity,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="orders",
        verbose_name="关联销售机会"  # 可选，从机会转化的订单
    )
    products = models.ManyToManyField(
        baseModels.FinishedModel,
        through="OrderItem",  # 关联中间表（含数量、单价）
        related_name="orders",
        verbose_name="产品"
    )
    total_amount = models.DecimalField("订单总金额", max_digits=12, decimal_places=2)
    status = models.CharField("状态", max_length=20, choices=ORDER_STATUS, default="pending")
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_orders",
        verbose_name="创建人"
    )
    created_at = models.DateTimeField("创建时间", default=timezone.now)

    def __str__(self):
        return self.order_no

    class Meta:
        verbose_name = "订单"
        verbose_name_plural = "订单"


# 订单与产品的中间表（记录数量、单价等）
class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(baseModels.FinishedModel, on_delete=models.CASCADE)
    quantity = models.IntegerField("数量", default=1)
    unit_price = models.DecimalField("单价", max_digits=10, decimal_places=2)  # 下单时的价格

    @property
    def total(self):
        return self.quantity * self.unit_price  # 小计金额

    class Meta:
        verbose_name = "订单明细"
        verbose_name_plural = "订单明细"